<template>
  <el-dialog :visible.sync="isShow" :title="title">
    <el-form ref="form" label-width="120px" :rules="rules" :model="form">
      <el-form-item prop="name" label="部门名称">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item prop="manager" label="部门负责人">
        <el-select
          v-model="form.manager"
          @focus="focusEvent"
        ><el-option
          v-for="i in userList"
          :key="i.id"
          :value="i.username"
          :label="i.username"
        /></el-select>
      </el-form-item>
      <el-form-item prop="introduce" label="部门介绍">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button type="primary" @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  sysUserSimple,
  companyDepartmentPost,
  companyDepartmentPut
} from '@/api/department.js'
export default {
  name: '',
  props: {
    initData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      mode: '',
      itemData: '',
      isShow: false,
      // 员工简单列表
      userList: [],
      form: {
        code: '', // 	string	非必须		部门编码，同级部门不可重复
        introduce: '', // sstring	非必须		介绍
        manager: '', // sstring	非必须		负责人名称
        name: '', // sstring	非必须		部门名称
        pid: '' // string	非必须		父级部门ID
      },
      rules: {
        code: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          },
          {
            validator: (rule, value, callback) => {
              // 判断子集中是否有与value中重名的项
              const bol = this.initData.some((item) => {
                if (this.mode === 'add') {
                  return item.code === value
                } else if (this.mode === 'edit') {
                  return item.code === value && item.id !== this.itemData.id
                }
              })
              bol ? callback(new Error('编码重复')) : callback()
            }
          }
        ],
        introduce: [
          {
            required: true,
            message: '必填',
            trigger: 'blur'
          }
        ],
        manager: [
          {
            required: true,
            message: '必填',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          },
          {
            validator: (rule, value, callback) => {
              const tempArr = this.initData.filter((item) => {
                if (this.mode === 'add') {
                  // 找出当前点击相的子集
                  return item.pid === this.itemData.id
                } else if (this.mode === 'edit') {
                  return (
                    // 找出排除自己的兄弟项
                    item.pid === this.itemData.pid &&
                    item.id !== this.itemData.id
                  )
                }
              })
              // 判断筛选出的项中是否有与value中重名的项
              const bol = tempArr.some((item) => item.name === value)
              bol ? callback(new Error('命名重复')) : callback()
            }
          }
        ]
      }
    }
  },
  // 动态title
  computed: {
    title() {
      return {
        add: '新增部门',
        edit: '编辑部门'
      }[this.mode]
    }
  },
  watch: {
    isShow(newVal) {
      if (!newVal) {
        // 重置表单和表单验证
        this.$refs.form.resetFields()
        // 重置
        this.form = {
          code: '', // 	string	非必须		部门编码，同级部门不可重复
          introduce: '', // sstring	非必须		介绍
          manager: '', // sstring	非必须		负责人名称
          name: '', // sstring	非必须		部门名称
          pid: '' // string	非必须		父级部门ID
        }
      }
    }
  },
  created() {},
  mounted() {
    this.$bus.$on('showDialog', (bol, itemData, mode) => {
      this.isShow = bol
      this.itemData = itemData
      this.form.pid = itemData.id
      this.mode = mode
      // 如果是编辑，数据回显
      if (mode === 'edit') {
        this.form = JSON.parse(JSON.stringify(itemData))
      }
    })
  },
  beforeDestroy() {
    this.$bus.$off('showDialog')
  },
  methods: {
    async focusEvent() {
      // 防止每次打开都请求
      if (this.userList.length === 0) {
        const res = await sysUserSimple()
        console.log(res)
        this.userList = res.data
        console.log(this.userList, 213123)
      }
    },
    // 点击确定
    submit() {
      this.$refs.form.validate(async(res) => {
        if (res) {
          if (this.mode === 'add') {
            await companyDepartmentPost(this.form)
            this.$message.success('添加成功')
          } else if (this.mode === 'edit') {
            await companyDepartmentPut(this.form)
            this.$message.success('编辑成功')
          }
          this.isShow = false
          // 刷新数据
          this.$emit('getDepartment')
        }
      })
    }
  }
}
</script>
<style lang="less" scoped></style>
